<template>
  <div>
    <div class="gui-padding bgf">
    <div class="mb15">
      <a-breadcrumb>
        <a-breadcrumb-item>权限管理</a-breadcrumb-item>
        <a-breadcrumb-item>用户管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="flex justify-content-between mb10">
      <div class="flex">
        <div>
          <span class="mr5"><a-button type="primary" size="small" :loading="addLoading" @click="handleAddOpen"> <template
              #icon><PlusOutlined/> </template>添加</a-button></span>
          <span class="mr5"><a-button type="primary" danger size="small" @click="handleOpenRecycle">
            <DeleteOutlined/>
            回收站
          </a-button></span>
          <span class="mr5"><a-button @click="handleBatchStatus" type="primary" size="small"
                                      :disabled="state.selectedRowKeys.length == 0"
                                      class="mainbg3"> <template #icon><ArrowUpOutlined/> </template>批量激活</a-button></span>
          <span class="mr5"><a-button @click="handleBatchForbidden" type="primary" size="small"
                                      :disabled="state.selectedRowKeys.length == 0"
                                      class="mainbg2"> <template #icon><ArrowDownOutlined/> </template>批量禁止</a-button></span>
          <span class="mr5"><a-button @click="handleBatchDel" type="primary" size="small"
                                      :disabled="state.selectedRowKeys.length == 0" danger> <template
              #icon><CloseOutlined/> </template>批量删除</a-button></span>
        </div>
      </div>
      <div>
        <a-form layout="inline" autocomplete="off" ref="searchFormRef" :model="queryParams">
          <a-form-item label="关键词" name="keyword">
            <a-input v-model:value.trim="queryParams.keyword" size="small" style="width: 160px"
                     placeholder="请输入关键词" allow-clear/>
          </a-form-item>
          <a-form-item label="状态" name="status">
            <a-select
                ref="select"
                size="small"
                placeholder="请选择"
                allow-clear
                v-model:value="queryParams.status"
                style="width: 120px"
            >
              <a-select-option :value="1">激活</a-select-option>
              <a-select-option :value="0">未激活</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <div class="flex">
              <a-button type="primary" size="small" @click="handleSearch">
                <SearchOutlined/>
                搜索
              </a-button>
              <a-button type="primary" danger size="small" @click="handleReset" class="ml10">
                <UndoOutlined/>
                重置
              </a-button>
            </div>
          </a-form-item>
        </a-form>
      </div>
    </div>
    <a-table
        :columns="columns"
        rowClassName="items"
        :loading="tableLoading"
        :scroll="{ x: 'calc(100vw - 326px)', y: 'calc(100vh - 245px)' }"
        rowKey="id"
        :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
        :pagination="false"
        :data-source="tableData"
        style="height:calc(100vh - 205px)"
        size="middle" sticky bordered>
      <template #bodyCell="{ column,text,record,index }">
        <template v-if="column.dataIndex==='username'">
          <div class="flex">
            <img :src="record.avatar" class="avatar" style="width: 24px;height: 24px;border-radius: 50%;">
            <span class="ml10">{{ record.username }}</span>
          </div>
        </template>
        <template v-if="column.dataIndex==='status'">
          <a-switch v-model:checked="record.status" @change="handleChangeUpdate(record,'status')"
                    
                    :checked-value="1"
                    :un-checked-value="0"
                    checked-children="激活中"
                    un-checked-children="未激活"/>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
             <span class="mr5">
              <a-button type="primary"  size="small" @click="handleEditOpen(record)"> <template
                  #icon><EditOutlined style="font-size:12px"/></template>编辑</a-button>
            </span>
            <span class="mr5">
              <a-button type="primary"  class="mainbg2" @click="handleUpdatePassword(record)"
                        size="small"> <template #icon><EditOutlined
                  style="font-size:12px"/></template>修改密码</a-button>
            </span>
            <span class="mr5">
              <a-button type="primary"  class="mainbg5" @click="handleBindRoles(record)"
                        size="small"> <template #icon><EditOutlined
                  style="font-size:12px"/></template>绑定角色</a-button>
            </span>
            <span class="mr5">
              <a-button type="primary"  class="mainbg5" @click="handleBindSystem(record)"
                        size="small"> <template #icon><EditOutlined
                  style="font-size:12px"/></template>绑定系统</a-button>
            </span>
            <a-popconfirm title="你确定删除吗?"  @confirm="handleDelete(record.id)">
              <a-button type="primary"  size="small" danger>
                <template #icon>
                  <CloseOutlined
                      style="font-size:12px"/>
                </template>
                删除
              </a-button>
            </a-popconfirm>
          </div>
        </template>
      </template>
    </a-table>
    <div class="flex  mt20">
      <a-pagination
          v-model:current="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          @change="handleChangePageNo"
          :page-size-options="pageSizeOptions"
          show-size-changer
          :total="total"/>
    </div>
    <add-user ref="addRef" @success="handleLoadData"></add-user>
    <user-recycle ref="recycleRef" @success="handleLoadData"></user-recycle>
    <user-password ref="passwordRef"></user-password>
    <user-bind-roles ref="bindRoleRef"></user-bind-roles>
    <user-bind-system ref="bindSystemRef"></user-bind-system>
  </div>
  </div>
</template>
<script setup>
import AddUser from "./compoments/AddUser.vue";
import UserRecycle from "./compoments/UserRecycle.vue";
import UserBindRoles from "./compoments/UserBindRoles.vue";
import UserBindSystem from "./compoments/UserBindSystem.vue";
import UserPassword from "./compoments/UserPassword.vue";

const recycleRef = ref(null)
const bindSystemRef = ref(null)
const bindRoleRef = ref(null)
const passwordRef = ref(null)
const addRef = ref(null)
const searchFormRef = ref(null)
const tableLoading = ref(false)
const addLoading = ref(false)
const total = ref(0)
const tableData = ref([]);
const pageSizeOptions = ref(['10', '20', '30', '40', '50']);
const queryParams = reactive({
  pageNo: 1,
  pageSize: 20,
  status: null,
  keyword: ''
})

// 控制表格checkbox选中
const state = reactive({
  selectedRowKeys: [],
  loading: false,
})

const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    align: "center",
    fixed: 'left',
    customRender: ({text, record, index}) => index + 1
  },
  {title: '主键', width: 200, dataIndex: 'id', align: "center", fixed: 'left'},
  {title: '昵称', width: 200, dataIndex: 'username', align: "center", fixed: 'left'},
  {title: '账号', dataIndex: 'account', width: 150, align: "center"},
  {title: '手机', dataIndex: 'phone', width: 100, align: "center"},
  {title: '邮箱', dataIndex: 'email', width: 200, align: "center"},
  {title: '是否管理员', dataIndex: 'admin', width: 150, align: "center"},
  {title: '状态', dataIndex: 'status', width: 150, align: "center"},
  {title: '创建时间', dataIndex: 'createTime', width: 150, align: "center"},
  {title: '更新时间', dataIndex: 'updateTime', width: 150, align: "center"},
  {
    title: '操作',
    dataIndex: 'operation',
    fixed: 'right',
    align: "center",
    width: 480,
  },
];


/**
 * 查询列表数据
 */
const handleLoadData = async () => {
  try {
    tableLoading.value = true
    const resp = await useLoadUserApi(queryParams)
    tableLoading.value = false
    tableData.value = resp.data.records
    total.value = resp.data.total
  } catch (e) {
    useMessage().error(e.msg)
  }
}

// 改变分页查询
const handleChangePageNo = (pno, psize) => {
  queryParams.pageNo = pno;
  queryParams.pageSize = psize;
  handleLoadData()
}

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1;
  handleLoadData()
}

const handleReset = () => {
  searchFormRef.value.resetFields()
  handleLoadData()
}

// 修改状态
const handleChangeUpdate = async (record, field) => {
  await useHandleUpdateStatusUserApi({id: record.id, field: field, value: record[field]})
  useMessage().success("操作成功!")
}

// 选择行
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys
};

/**
 * 删除逻辑
 * @param id
 * @returns {Promise<void>}
 */
const handleDelete = async (id) => {
  try {
    await useDelUserApi(id)
    notification.destroy()
    notification.success({
      "message": "提示",
      "description": "删除成功"
    })
    handleLoadData()
  }catch (e){
    useMessage().error(e.msg)
  }

}

// 打开添加
const handleAddOpen = () => {
  addRef.value.handleOpen()
}

// 编辑处理
const handleEditOpen = (record) => {
  addRef.value.handleOpen({...record})
}

// 打开回收站modal
const handleOpenRecycle = () => {
  recycleRef.value.handleOpen()
}

// 打开修改密码modal
const handleUpdatePassword = (record) => {
  passwordRef.value.handleOpen(record)
}

// 打开绑定角色modal
const handleBindRoles = (record) => {
  bindRoleRef.value.handleOpen(record.id)
}

// 打开绑定系统modal
const handleBindSystem = (record) => {
  bindSystemRef.value.handleOpen(record.id)
}

// 批量处理-删除
const handleBatchDel = async () => {
  var keys = [...state.selectedRowKeys]
  await useBatchDelsApi({ids: keys})
  state.selectedRowKeys = []
  handleLoadData();
}
// 批量处理-激活
const handleBatchStatus = async () => {
  var keys = [...state.selectedRowKeys]
  await useBatchStatusApi({ids: keys})
  state.selectedRowKeys = []
  handleLoadData();
}
// 批量处理-禁止
const handleBatchForbidden = async () => {
  var keys = [...state.selectedRowKeys]
  await useBatchForbiddensApi({ids: keys})
  state.selectedRowKeys = []
  handleLoadData();
}

onMounted(() => {
  handleLoadData()
})

</script>

